package czy.demo.config;

import czy.demo.pojo.Person;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.Set;

/* MongoDB配置类 */
@Configuration
public class MongoDBConfig implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(MongoDBConfig.class);

    @Autowired
    private MongoTemplate template;

    /* 在Mongodb里每个类映射为一个集合 */
    @Override
    public void afterPropertiesSet() throws Exception {
        Set<String> names = this.template.getCollectionNames();
        for(String name:names){
            logger.info("发现集合："+name);
        }
        /* 如果集合不存在则创建他 */
        if(!this.template.collectionExists(Person.class)){
            this.template.createCollection(Person.class);
        }
    }
}
